package reflect;
import java.lang.reflect.Field;
/**
 * 通过反射机制访问属性
 */
public class ReflectDemo8 {
    public static void main(String[] args) throws Exception {
        Class cls = Class.forName("reflect.Person");
        Object obj = cls.newInstance();
        /*
         Field是反射对象之一，用于表示属性
         */
        Field field = cls.getDeclaredField("name"); //获取name属性
        field.setAccessible(true);  //强制打开访问权限
        field.set(obj,"张三");    //obj.name = "张三";
        String name = (String) field.get(obj);  //String name = obj.name;
        field.setAccessible(false); //关闭访问权限

        Field field1 = cls.getDeclaredField("age");
        field1.setAccessible(true);
        field1.set(obj,25);
        field1.setAccessible(false);
        System.out.println("名字："+name);
        System.out.println(obj);
    }
}
